import { mapGetters, mapMutations, mapActions } from 'vuex'
import { playMode } from 'common/js/config'
import { shuffle } from 'common/js/utils'

export const playlistMixin = {
  mounted () {
    this.handlePlaylist(this.playlist)
  },
  activated () {
    // keep-alive 激活时触发
    this.handlePlaylist(this.playlist)
  },
  computed: {
    ...mapGetters([
      'playlist'
    ])
  },
  watch: {
    playlist (newVal) {
      this.handlePlaylist(newVal)
    }
  },
  methods: {
    handlePlaylist () {
      throw new Error('component must be implement handlePlaylist method')
    }
  }
}

export const playerMixin = {
  computed: {
    iconMode () {
      if (this.mode === playMode.sequence) {
        return 'icon-sequence'
      } else if (this.mode === playMode.loop) {
        return 'icon-loop'
      } else {
        return 'icon-random'
      }
    },
    ...mapGetters([
      'sequenceList',
      'currentSong',
      'mode',
      'playlist',
      'favoriteList'
    ])
  },
  methods: {
    handleModeChange () {
      // %3 的作用是让结果在 0、1、2 之间循环
      const newMode = (this.mode + 1) % 3
      this.setModeState(newMode)

      let list = null
      if (newMode === playMode.random) {
        // 随机播放
        list = shuffle(this.sequenceList)
      } else {
        // 顺序、循环播放
        list = this.sequenceList
      }
      this.resetCurrentIndex(list)
      this.setPlayList(list)
    },
    resetCurrentIndex (list) {
      // 从 list 中找到当前播放歌曲 currentSong 对应的索引
      const index = list.findIndex((item) => {
        return item.rid === this.currentSong.rid
      })
      this.setCurrentIndex(index)
    },
    getFavoriteIcon (song) {
      return this.isFavorite(song) ? 'icon-favorite' : 'icon-not-favorite'
    },
    toggleFavorite (song) {
      if (this.isFavorite(song)) {
        // 返回 true，说明已收藏，那么就将它删除
        this.deleteFavoriteList(song)
      } else {
        // 返回 false，说明未收藏，那么就将它收藏
        this.saveFavoriteList(song)
      }
    },
    isFavorite (song) {
      let index = this.favoriteList.findIndex((item) => {
        return item.rid === song.rid
      })
      // index > -1 说明找到了
      return index > -1
    },
    ...mapMutations({
      setCurrentIndex: 'SET_CURRENT_INDEX',
      setModeState: 'SET_MODE_STATE',
      setPlayList: 'SET_PLAYLIST',
      setPlayingState: 'SET_PLAYING_STATE'
    }),
    ...mapActions([
      'saveFavoriteList',
      'deleteFavoriteList'
    ])
  }
}

export const searchMixin = {
  data () {
    return {
      query: ''
    }
  },
  computed: {
    ...mapGetters([
      'searchHistory'
    ])
  },
  methods: {
    handleQueryChange (query) {
      this.query = query
    },
    blurInput () {
      this.$refs.searchBox.blur()
    },
    ...mapActions([
      'saveSearchHistory',
      'deleteSearchHistory'
    ])
  }
}
